package jupiter.servlets;



import javax.servlet.http.*;

import jupiter.messaging.ApplicationAddressBook;
import jupiter.messaging.Inbox;
import jupiter.messaging.Jabbify;
import jupiter.messaging.Message;
import jupiter.util.Timey;


import org.mortbay.util.ajax.Continuation;
import org.mortbay.util.ajax.ContinuationSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import org.json.*;



public class JabbifyServlet extends HttpServlet {
	public static final int TIMEOUT_SECS = 59;
	Logger logger = LoggerFactory.getLogger(JabbifyServlet.class);
	public void service(HttpServletRequest req, HttpServletResponse res) throws java.io.IOException {
		String result = null;
		HttpSession session = null;
		try{
			if(! Jabbify.filterVersion(req, res)) return;
			session = req.getSession(false);
			if(session == null){
				res.getWriter().flush();
				return;
			}
			Inbox inbox = (Inbox) session.getAttribute("Inbox");
			if(inbox == null){
				res.getWriter().print("alert('your session does not have a user!');");
				res.getWriter().flush();
			}
			result = "null";
			result = inbox.getMessages();

		}catch(RuntimeException e){
			logger.error(e.getClass().toString(), e);
			throw e;
	    }catch(Exception e){
			logger.error("Exception in JabbifyServlet", e);
	    }
		if(result == "null"){ //lets try again when something comes in
			Continuation c = ContinuationSupport.getContinuation(req,null);
			ApplicationAddressBook.addContinuation(c, session, TIMEOUT_SECS);
		}

		try{
			Timey ta = new Timey();

	//		int n = (int)(10.0 * Math.random()) + 1;
	//		System.out.println("n: "+ n);
	//		if(n<4){
	//			res.setStatus(500);
	//			res.setContentType("text/javascript; charset=utf-8");
	//			res.getWriter().print("error");
	//		} else{
			String callback = req.getParameter("callback");
			String nocallback = req.getParameter("nocallback");
			if(nocallback == null){
				res.setContentType("text/javascript; charset=utf-8");
				res.getWriter().print(callback+"("+result+")");
			}
			else{
				res.setContentType("text/plain");
				res.getWriter().print(result);
			}
		    res.getWriter().flush();
		    
		    ta.end("JabbifyAfter");
			
//			}
		}catch(RuntimeException e){
			logger.error(e.getClass().toString(), e);
			throw e;
	    }catch(Exception e){
			logger.error("Exception in JabbifyServlet", e);
	    }
	}

	
}
